#include <stdio.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <unistd.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <stdlib.h>
#include <errno.h>
#include <string.h>
#include <time.h>

#define IPADDRESS	"127.0.0.100"
#define PORT		13

static void
error(char *msg)
{
    fputs(strerror(errno), stderr);
    fputs(": ", stderr);
    fputs(msg, stderr);
    fputc('\n', stderr);
    exit(1);
}

int main(int argc, char **argv)
{
    int z;	//status return code
    int s;	// server socket fd
    int c;	// client socket fg
    int n;

    struct sockaddr_in adr_srvr;	//server socket address
    struct sockaddr_in adr_clnt;	//client socket address

    size_t len_srvr, len_clnt;			//length of server socket address
    
    time_t td;				//current date and time
    char dtbuff[128];			//date and time format

    //create server socket
    s = socket(AF_INET, SOCK_STREAM, 0);
    if ( s == -1 )
	error("socket()");

    //initialize server socket
    memset(&adr_srvr, 0, sizeof(adr_srvr));
    adr_srvr.sin_family = AF_INET;
    adr_srvr.sin_port = htons(PORT);
    if ( inet_aton(IPADDRESS, &adr_srvr.sin_addr) < 0 )
	error("inet_aton()");

    len_srvr = sizeof(adr_srvr);

    //bind server socket to the address
    z = bind(s, (struct sockaddr *) &adr_srvr, len_srvr);
    if ( z < 0 )
	error("bind()");

    //place server in listening mode
    z = listen(s, 5);
    if ( z < 0 )
	error("listen()");

    for ( ; ; ) {
	len_clnt = sizeof(adr_clnt);
	//create client socket address
	c = accept(s, (struct sockaddr *) &adr_clnt, &len_clnt);
	if ( c == -1 )
	    error("accept()");

	time(&td);
	n = strftime(dtbuff, sizeof(dtbuff), "%A %b %d %H:%M%S %Y\n", localtime(&td));

	//write result back to the client
	z = write(c, dtbuff, n);
	if ( z < 0 )
	    error("write()");

	close(c);
    }

    close(s);

    return 0;
}
